@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion

echo [调试] 开始执行脚本...

:: ==============================================
:: 管理员检查
:: ==============================================
echo [调试] 检查管理员权限...
fltmc >nul 2>&1 || (
    echo [错误] 需要管理员权限!
    echo 请右键"以管理员身份运行"
    pause
    exit /b 1
)
echo [调试] 管理员权限检查通过

:: 配置参数
set "PY_VER=3.11.9"
set "DIR=%~dp0..\python"
echo [调试] 工作目录: %DIR%

:: ==============================================
:: 智能架构检测（注册表优先+环境变量备用）
:: ==============================================
echo [调试] 开始检测系统架构...
set "ARCH=unknown"

:: 第一阶段：注册表检测（最可靠）
echo [调试] 尝试从注册表检测架构...
for /f "tokens=2*" %%i in ('reg query "HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0" /v "Identifier" 2^>nul') do (
    if /i "%%j"=="x86" (
        set "ARCH=32"
        echo [注册表] 32位架构^(x86^)
    ) else if /i "%%j"=="x64" (
        set "ARCH=64"
        echo [注册表] 64位架构^(x64^)
    ) else if /i "%%j"=="ARM" (
        set "ARCH=ARM"
        echo [注册表] ARM架构
    )
)

:: 第二阶段：Itanium专用检测
if "%ARCH%"=="unknown" (
    echo [调试] 尝试Itanium架构检测...
    for /f "tokens=2*" %%i in ('reg query "HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0" /v "Platform ID" 2^>nul') do (
        if "%%j"=="20" (
            set "ARCH=64"
            echo [注册表] Itanium架构^(IA64^)
        )
    )
)

:: 第三阶段：环境变量备用检测
if "%ARCH%"=="unknown" (
    echo [调试] 尝试从环境变量检测架构...
    if defined PROCESSOR_ARCHITECTURE (
        if /i "%PROCESSOR_ARCHITECTURE%"=="AMD64" (
            set "ARCH=64"
            echo [环境变量] 64位系统^(AMD64^)
        ) else if /i "%PROCESSOR_ARCHITECTURE%"=="ARM64" (
            set "ARCH=ARM"
            echo [环境变量] ARM架构
        )
    )
)

:: 最终回退方案
if "%ARCH%"=="unknown" (
    set "ARCH=32"
    echo [警告] 无法检测架构，默认32位^(x86^)
)

:: ==============================================
:: 根据架构设置下载URL
:: ==============================================
echo [调试] 设置下载URL...
set "URL=https://mirrors.huaweicloud.com/python/%PY_VER%/python-%PY_VER%-embed-"
if "%ARCH%"=="64" (
    set "URL=%URL%amd64.zip"
) else if "%ARCH%"=="ARM" (
    set "URL=%URL%arm64.zip"
) else (
    set "URL=%URL%win32.zip"
)

echo [最终结果] 系统架构: %ARCH%
echo [下载链接] %URL%

:: [1/6] 创建目录
echo [1/6] Creating directory...
echo [调试] 尝试创建目录: %DIR%
if not exist "%DIR%" mkdir "%DIR%" 2>nul
if not exist "%DIR%" (
    echo [错误] 无法创建目录: %DIR%
    pause
    exit /b 1
)
echo [调试] 目录创建成功

:: [2/6] 下载Python
echo [2/6] Downloading Python...
echo [调试] 开始下载Python...
powershell -command "$ProgressPreference='SilentlyContinue'; (New-Object Net.WebClient).DownloadFile('%URL%', '%DIR%\python.zip')"
if not exist "%DIR%\python.zip" (
    echo [错误] 下载Python失败
    pause
    exit /b 1
)
echo [调试] Python下载完成

:: [3/6] 解压文件
echo [3/6] Extracting files...
echo [调试] 开始解压文件...
powershell -command "Expand-Archive -Path '%DIR%\python.zip' -DestinationPath '%DIR%' -Force"
if not exist "%DIR%\python.exe" (
    echo [错误] 解压Python失败
    pause
    exit /b 1
)
echo [调试] 文件解压完成

:: [4/6] 动态生成.pth配置
echo [4/6] 配置Python路径...
echo [调试] 开始配置Python路径...
:: 提取主版本号（如3.11.9 -> 311）
for /f "tokens=1,2 delims=." %%A in ("%PY_VER%") do (
    set "MAJOR=%%A"
    set "MINOR=%%B"
)
set "_PTH_FILE=%DIR%\python%MAJOR%%MINOR%._pth"
echo [调试] .pth文件路径: %_PTH_FILE%

if exist "%_PTH_FILE%" (
    echo [调试] 已存在.pth文件，开始修改...
    findstr /C:"Lib/site-packages" "%_PTH_FILE%" >nul || (
        echo [配置] 添加标准库路径
        echo Lib\site-packages >> "%_PTH_FILE%"
    )
    :: 检查ComfyUI路径（精确匹配整行）
    findstr /X /C:"./../ComfyUI" "%_PTH_FILE%" >nul || (
        echo [配置] 添加ComfyUI路径
        echo .\..\ComfyUI >> "%_PTH_FILE%"
    )

    :: 检查根路径（精确匹配且规范格式）
    findstr /X /C:"./../" "%_PTH_FILE%" >nul || (
        echo [配置] 添加根路径
        echo .\..\ >> "%_PTH_FILE%"
    )
) else (
    echo [调试] 创建新的.pth文件...
    (
        echo python%MAJOR%%MINOR%.zip
        echo .
        echo Lib\site-packages
        echo .\..\ComfyUI
        echo .\..\
    ) > "%_PTH_FILE%"
)

:: 验证
if not exist "%_PTH_FILE%" (
    echo [错误] 无法创建.pth文件
    pause
    exit /b 1
)
echo [调试] .pth文件配置完成

:: [5/6] 强制重装pip
echo [5/6] Reinstalling pip...
cd /d "%DIR%"

echo [调试] 开始安装pip...
python.exe -m ensurepip --upgrade
if errorlevel 1 (
    echo [错误] 使用ensurepip安装失败
    echo [调试] 尝试使用get-pip.py安装...
    
    echo [调试] 开始下载get-pip.py...
    echo [调试] 下载地址: https://mirrors.aliyun.com/pypi/get-pip.py
    echo [调试] 保存位置: %DIR%\get-pip.py

    :: 使用curl下载get-pip.py
    curl -L -o "%DIR%\get-pip.py" https://mirrors.aliyun.com/pypi/get-pip.py
    if not exist "%DIR%\get-pip.py" (
        echo [错误] 下载get-pip.py失败
        echo [调试] 请检查网络连接或手动下载get-pip.py
        pause
        exit /b 1
    )

    echo [调试] get-pip.py下载完成
    echo [调试] 文件大小: 
    dir "%DIR%\get-pip.py"

    echo [调试] 开始安装pip...
    python.exe get-pip.py --force-reinstall --no-warn-script-location
    if errorlevel 1 (
        echo [错误] 安装pip失败
        echo [调试] 请检查Python安装是否正确
        pause
        exit /b 1
    )
)
echo [调试] pip安装完成

:: [6/6] 验证安装
echo [6/6] Verifying installation...
echo [调试] 开始验证安装...
set "PYTHONPATH=%DIR%\Lib\site-packages;%DIR%\Scripts"
python.exe -c "import sys; print(sys.path); import pip; print('Pip version:', pip.__version__)"
if errorlevel 1 (
    echo [错误] Pip验证失败
    pause
    exit /b 1
)
echo [调试] 安装验证完成

:: 设置临时环境变量
echo [调试] 设置环境变量...
set PATH=%PATH%;%DIR%;%DIR%\Scripts

echo.
echo [成功] Python和pip已准备就绪！
echo [提示] 临时PATH已设置（仅当前CMD窗口有效）
echo [提示] 如需永久生效，请将以下路径添加到系统PATH：
echo   %DIR%
echo   %DIR%\Scripts

echo.
echo [完成] 按任意键退出...

pause
exit /b 0 